package com.code.aspect;

import com.code.commons.constants.ServerConstants;
import com.code.commons.enums.ResultCode;
import com.code.commons.exceptions.BusinessException;
import com.code.commons.web.annotations.ProdLimit;
import com.code.config.profile.ProfileConfig;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 线上禁止调用的接口
 *
 * @author tangyifei
 * @since 2020年2月7日16:46:31
 */
@Aspect
@Configuration
@Slf4j
public class ProdLimitAspect {

    @Resource
    private ProfileConfig profileConfig;

    @Around("execution(* com.code.web ..*(..) )")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ProdLimit prodLimit = method.getAnnotation(ProdLimit.class);

        if (null != prodLimit) {
            String profile = profileConfig.getActiveProfile();
            if (!ServerConstants.PROD.equals(profile)) {
                return joinPoint.proceed();
            } else {
                throw new BusinessException(ResultCode.PROD_METHOD_NO_AUTH_CALL);
            }
        } else {
            return joinPoint.proceed();
        }

    }
}
